package com.springboot.demo.seria_deseria.core;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用上下文
 *
 * @author XiaoQingqing
 * @since 2024/01/08
 */
public class CommonContext {
    /**
     * 上下文内容
     */
    private static final ThreadLocal<Map<CommonContextKeyEnum, Object>> CONTENT = new TransmittableThreadLocal<>();

    /**
     * 设置值
     *
     * @param key   键
     * @param value 值
     * @param <T>   值类型
     */
    public static <T> void set(CommonContextKeyEnum key, T value){
        Map<CommonContextKeyEnum, Object> contextMap = CONTENT.get();
        if(null == contextMap){
            contextMap = new HashMap<>();
            CONTENT.set(contextMap);
        }
        contextMap.put(key, value);
    }

    /**
     * 获取值
     *
     * @param key 键
     * @return 值
     * @param <T> 值类型
     */
    @SuppressWarnings("unchecked")
    public static <T> T get(CommonContextKeyEnum key){
        Map<CommonContextKeyEnum, Object> contextMap = CONTENT.get();
        return null == contextMap ? null : (T)contextMap.get(key);
    }

    /**
     * 清空上下文
     */
    public static void clear(){
        CONTENT.remove();
    }

}
